import React, { useState, useEffect, MouseEvent } from 'react';
import { Card, Button, Empty, List, Typography } from 'antd';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { SvgIcon } from '@/components/icon';
import datasetService from '@/api/services/datasetService';
import appService from '@/api/services/appService';
import { DatasetTypeEnum } from '@/common/types/dataset/dataset';
import { useLocation } from 'react-router-dom';

import NotData from '@/components/NotData';
import orgService from '@/api/services/orgService';
import { useRequest } from 'ahooks';


const { Text } = Typography;

interface KnowledgeBaseProps {
  onSwitchToKnowledgeTab: (contentType: 'datasets' | 'api-manage' | 'extension-manage' | 'nl2sql-manage') => void;
  isPreview: boolean;
}

interface DatasetStats {
  count: number;
  totalFiles: number;
  apiCount: number;
  appCount: number;
}

// 应用扩展数据的类型定义
interface ExtensionCategory {
  category: string;
  page_data: {
    list: Array<any>;
    total: number;
    page: number;
    page_size: number;
  };
}

// 定义路径映射
const pathMap = {
  file: '/know/datasets/list',
  api: '/know/datasets/api',
  app: '/know/extension/manage'
};

const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onSwitchToKnowledgeTab, isPreview }) => {
  const [showTips, setShowTips] = useState(true);
  const [nl2sqlNum, setNl2sqlNum] = useState(0);
  const [loading, setLoading] = useState(false);
  const { datasetStats, setDatasetStats, userRole, configurations } = useOrchestrationStore();

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || "";

  // 检查是否没有任何数据
  const hasNoData = datasetStats.count === 0 && datasetStats.apiCount === 0 && datasetStats.appCount === 0 && nl2sqlNum === 0;

  const isEnableApplicationRecommend = configurations?.find(
    (config) => config.name === 'enable_application_recommend',
  );

  const { run: fetchNl2sqlNum } = useRequest(
    () => orgService.getDatasetNl2sql({ appId: appId }),
    {
      manual: true,
      onSuccess: (res) => {
        setNl2sqlNum(res?.list?.length || 0);
      },
    }
  );

  useEffect(() => {
    if (appId) {
      fetchNl2sqlNum();
    }
  }, [appId]);

  const isEnableNl2sql = configurations?.find(
    (config) => config.name === 'enable_nl2sql',
  );
  const isEnableNl2sqlDataset =
    configurations?.find((config) => config.name === 'enable_nl2sql_dataset')?.default_value === '1' ||
    false;

  const isEnableFunctionCalling = configurations?.find(
    (config) => config.name === 'enable_function_calling',
  );

  // 获取知识库、数据接口和应用管理数量
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        // 获取所有知识库
        // const datasets = await datasetService.datasetList({
        //   app_id: appId,
        //   parentId: null
        // });
        const datasets = await datasetService.getDatasetList({
          app_id: appId,
          isPage: false,
          parentId: '',
        })

        // 在前端根据类型过滤和统计
        const fileDatasets = datasets?.list?.filter(item => item.type === DatasetTypeEnum.dataset);
        const apiDatasets = datasets?.list?.filter(item => item.type === DatasetTypeEnum.api);

        console.log('fileDatasets', datasets)

        // 获取应用数量
        const extensionData = await appService.extensionList({ app_id: appId }) as ExtensionCategory[];
        // 计算应用总数（可能包含多个分类）
        const appCount = extensionData.reduce((total: number, category: ExtensionCategory) =>
          total + (category.page_data?.list?.length || 0), 0);

        const newDatasetStats = {
          count: fileDatasets.length,
          totalFiles: fileDatasets.reduce((total, dataset) => total + (dataset.count || 0), 0),
          apiCount: apiDatasets.length,
          appCount: appCount
        };

        setDatasetStats(newDatasetStats);
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    // fetchData();
  }, [appId, setDatasetStats]);

  // 创建处理函数
  const handleFileClick = () => {
    onSwitchToKnowledgeTab('datasets');
  };

  const handleApiClick = () => {
    onSwitchToKnowledgeTab('api-manage');
  };

  const handleAppClick = () => {
    onSwitchToKnowledgeTab('extension-manage');
  };

  const handleNl2sqlClick = () => {
    onSwitchToKnowledgeTab('nl2sql-manage');
  };

  const handleCloseTips = () => {
    setShowTips(false);
  };

  // 如果没有任何知识来源
  const renderEmptyState = () => (
    <Card className="orch-card-body [-ms-overflow-style:none] [scrollbar-width:none] mb-4 border-[transparent] h-full">
      {showTips && !isPreview && (
        <div className="p-4 bg-[#F0F7FF] rounded-[6px]">
          {userRole === 'admin' ? (
            <>
              <div className="flex justify-between items-center mb-2">
                <Text className="font-medium !text-[14px] text-[#1A1E26]">添加知识文档以提高回答质量</Text>
                {/* <Button type="text" icon={<CloseOutlined />} className="text-[#86909C]" onClick={handleCloseTips} /> */}
              </div>
              <div className="text-[#86909C] font-normal !text-[12px] ">你可以尝试添加以下相关内容：</div>
              <div className="text-[#86909C] font-normal !text-[12px] ">
                <div>1. 核心文档（手册/方案/说明书）</div>
                <div>2. 规范文件（政策/指南/标准）</div>
                <div>3. 扩展资源（数据/案例/年报）</div>
                <div>4. 动态平台（门户/资源网站）</div>
              </div>
            </>
          ) : (
            <>
              <div className="flex justify-between items-center mb-4">
                <Text style={{ fontWeight: 400, fontSize: '16px', color: '#131313' }}>您是当前应用的知识库管理员</Text>
                {/* <Button type="text" icon={<CloseOutlined />} className="text-[#86909C]" onClick={handleCloseTips} /> */}
              </div>
              <Text style={{ fontWeight: 400, fontSize: '14px', color: '#636363' }} className="block mb-4">
                可以增加、删除、修改知识库的文件
              </Text>
              <Text style={{ fontWeight: 400, fontSize: '14px', color: '#FA5757' }} className="block">
                注意：增加、删除、修改文件后可在问答页面测试，点击"发布"后普通用户的问答内容才会更新。
              </Text>
            </>
          )}
        </div>
      )}

      {!hasNoData && (
        <div className={showTips ? "mt-6" : "mt-0"}>
          {/* 知识文件区域 */}
          <div className="flex items-center justify-between p-4 border-t border-[transparent] bg-[#9C9C9C1A] rounded-[6px] mb-4">
            <div className="flex items-center">
              <div className="mr-4">
                <SvgIcon icon="knowledge" style={{ fontSize: '24px' }} />
              </div>
              <div>
                <Text className="block text-[#1D2129]">知识文件</Text>
                {datasetStats.count > 0 ? (
                  <Text className="block !text-[12px] text-[#86909C]">
                    已有{datasetStats.count}个知识库，共{datasetStats.totalFiles}个文件
                  </Text>
                ) : (
                  <Text className="block !text-[12px] text-[#86909C]">暂无数据</Text>
                )}
              </div>
            </div>
            <Button type="link" onClick={handleFileClick} disabled={isPreview}>
              管理
            </Button>
          </div>

          {/* 数据接口区域 */}
          {userRole === 'admin' && isEnableFunctionCalling &&
            <div className="flex items-center justify-between p-4 border-t border-[transparent] bg-[#9C9C9C1A] rounded-[6px] mb-4">
              <div className="flex items-center">
                <div className="mr-4">
                  <SvgIcon icon="interface" style={{ fontSize: '24px' }} />
                </div>
                <div>
                  <Text className="block text-[#1D2129]">数据接口</Text>
                  {datasetStats.apiCount > 0 ? (
                    <Text className="block !text-[12px] text-[#86909C]">
                      已有{datasetStats.apiCount}个数据接口
                    </Text>
                  ) : (
                    <Text className="block !text-[12px] text-[#86909C]">暂无数据</Text>
                  )}
                </div>
              </div>
              <Button type="link" className="text-[#7B67EE]" onClick={handleApiClick} disabled={isPreview}>
                管理
              </Button>
            </div>
          }

          {/* 应用管理区域 */}
          {userRole === 'admin' && isEnableApplicationRecommend &&
            <div className="flex items-center justify-between p-4 border-t border-[transparent] bg-[#9C9C9C1A] rounded-[6px] mb-4">
              <div className="flex items-center">
                <div className="mr-4">
                  <SvgIcon icon="application" style={{ fontSize: '24px' }} />
                </div>
                <div>
                  <Text className="block text-[#1D2129]">业务管理</Text>
                  {datasetStats.appCount > 0 ? (
                    <Text className="block !text-[12px] text-[#86909C]">
                      已有{datasetStats.appCount}个业务
                    </Text>
                  ) : (
                    <Text className="block !text-[12px] text-[#86909C]">暂无数据</Text>
                  )}
                </div>
              </div>
              <Button type="link" className="text-[#7B67EE]" onClick={handleAppClick} disabled={isPreview}>
                管理
              </Button>
            </div>
          }

          {/* NL2SQL区域 */}
          {userRole === 'admin' && (isEnableNl2sqlDataset || isEnableNl2sql) &&
            <div className="flex items-center justify-between p-4 border-t border-[transparent] bg-[#9C9C9C1A] rounded-[6px] mb-4">
              <div className="flex items-center">
                <div className="mr-4">
                  <SvgIcon icon="ai-orch-nl2sql" style={{ fontSize: '24px' }} />
                </div>
                <div>
                  <Text className="block text-[#1D2129]">数据库问答管理</Text>
                  {nl2sqlNum > 0 ? (
                    <Text className="block !text-[12px] text-[#86909C]">
                      已有{nl2sqlNum}个数据库问答知识库
                    </Text>
                  ) : (
                    <Text className="block !text-[12px] text-[#86909C]">暂无数据</Text>
                  )}
                </div>
              </div>
              <Button type="link" className="text-[#7B67EE]" onClick={handleNl2sqlClick} disabled={isPreview}>
                管理
              </Button>
            </div>
          }
        </div>
      )}

      {/* 当所有数量为0时显示"去添加"按钮 */}
      {hasNoData && (
        <div className={`${showTips ? "mt-16" : "mt-10"} flex flex-col items-center justify-center`}>
          {/* <div>
            <SvgIcon icon="ic_setting_empty" style={{ fontSize: '80px' }} />
          </div>
          <Text className="block !text-[12px] text-[#86909C]">暂无数据</Text> */}
          <NotData />

          <div className="flex justify-center mt-4 mb-2">
            <Button
              type="primary"
              disabled={isPreview}
              className="bg-[#7B67EE] hover:bg-[#9586F0] px-8"
              onClick={() => onSwitchToKnowledgeTab('datasets')}
              size="middle"
            >
              去添加
            </Button>
          </div>
        </div>
      )}
    </Card>
  );

  return renderEmptyState();
};

export default KnowledgeBase; 